package xmlParsers;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import negocio.Item_Compra;
import negocio.OrdenCompra;

public class XmlBuildOrdenCompra {


	private static XmlBuildOrdenCompra instancia;

	private DocumentBuilderFactory factory;
	
	private XmlBuildOrdenCompra(){
		this.factory=DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
	}
	

	public static XmlBuildOrdenCompra getinstancia(){
		if(instancia==null)
			instancia=new XmlBuildOrdenCompra();
		return instancia;
	}
	
	
	public String createXmlOrden(OrdenCompra o) throws ParserConfigurationException, TransformerException{
		
		DocumentBuilder builder= this.factory.newDocumentBuilder();
		Document doc = builder.newDocument();
		
		Element root = doc.createElement(o.getProveedor());
		doc.appendChild(root);
		
		
		Calendar calendar= Calendar.getInstance();
		calendar.setTime(new Date());
		
		int dia=calendar.get(Calendar.DAY_OF_MONTH);
		int mes=calendar.get(Calendar.MONTH);
		int anio=calendar.get(Calendar.YEAR);
		String s=(dia +"/"+mes+"/"+anio);
		
		
		SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);    
		String ven = dateformat.format(cal.getTime());
		
		
		
		
		
		root.setAttribute("fecha", s);
		root.setAttribute("vencimiento", ven);
		root.setAttribute("numero_Orden", Integer.toString(o.getNumeroOrden()));
		
		Element productos=doc.createElement("productos");
		root.appendChild(productos);
		
		for(Item_Compra i : o.getItemsCompra()){
			Element nombre=doc.createElement("nombre");
			nombre.setTextContent(i.getProducto().getNombre());
			
			Element cantidad=doc.createElement("cantidad");
			cantidad.setTextContent(Float.toString(i.getCantidad()));
			
			productos.appendChild(nombre);
			productos.appendChild(cantidad);
	
			
		}
		
		s=dia+"-"+mes+"-"+anio;
		String path="xmls/"+o.getProveedor()+s+".xml";
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(path));
        
		transformer.transform(source, result);

		
		return path;
		
		
	}
	
	
	

}
